#!/usr/bin/env python
# -*- coding: utf-8 -*-

'''
PNL - Plurk Now Listening. When you listen to music, this program will post a 
plurk include what you listening and a youtube url of this music.
Copyright (C) 2011 Ryan Ho

This program is free software; you can redistribute it and/or modify it under 
the terms of the GNU General Public License as published by the Free Software 
Foundation; either version 2 of the License, or (at your option) any later 
version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY
 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR 
 A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with 
this program; if not, write to the Free Software Foundation, Inc., 59 Temple 
Place, Suite 330, Boston, MA 02111-1307 USA

'''

import sys, plurklib
from PyQt4 import QtGui
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from helper import MPRIS, YoutubeAPI
import optionui

P_API_Key = 'tZ9PNES74iR6r5hDwS1yeq8JN2jvjVQ4'

class mainWidget(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.settings = QSettings('RyanHo','pnl')
        self.resize(0,0)
        
        self.menu = QMenu(self)
        self.menu.setObjectName('menu')
        self.Playerstatus = QAction('Player Status', self)
        self.Playerstatus.setObjectName('Playerstatus')
        self.menu.addAction(self.Playerstatus)
        self.PlurkStatus = QAction('Plurk Status', self)
        self.PlurkStatus.setObjectName('PlurkStatus')
        self.menu.addAction(self.PlurkStatus)
        self.opt_window = QAction('Option', self)
        self.opt_window.setObjectName('opt_window')
        self.menu.addAction(self.opt_window)
        self.Exitaction = QAction('Exit', self)
        self.Exitaction.setObjectName('Exitaction')
        self.menu.addAction(self.Exitaction)
        
        self.W_Icon = QIcon('pnl.png')
        
        self.SystrayIcon = QSystemTrayIcon(self)
        self.SystrayIcon.setContextMenu(self.menu)
        self.SystrayIcon.setIcon(self.W_Icon)
        self.SystrayIcon.show()
        
        self.updatetimer = QTimer(self)
        self.updatetimer.setObjectName('updatetimer')
        self.plurk = plurklib.PlurkAPI(P_API_Key)
        
        self.player = MPRIS()
        self.m_title = self.player.get_meta()[1]
        
        if self.checkPlayer():
            self.playerstatus = '%s - %s (%s)' % (self.player.get_meta())
            self.Playerstatus.setText(self.playerstatus)
        
        self.videosearch = YoutubeAPI()
        
        self.plurk_login()
        
        self.updatetimer.start(3000)
        
        QMetaObject.connectSlotsByName(self)
        
    def checkPlayer(self):
        if self.player.get_meta() == 'No MPRIS-compliant player found running.':
            self.Playerstatus.setText(self.player.get_meta())
            return False
        else:
            self.Playerstatus.setText('%s - %s (%s)' % (self.player.get_meta()))
            return True
             

    @pyqtSlot()
    def on_Exitaction_triggered(self):
        sys.exit()
        
    @pyqtSlot()
    def on_updatetimer_timeout(self):
        if self.checkPlayer():
            if self.player.get_meta()[1] == self.m_title:
                return
            else:
                self.m_title = self.player.get_meta()[1]
                artist, title, album = self.player.get_meta()
                nowlistening = '%s - %s (%s)' % (self.player.get_meta())
                self.Playerstatus.setText(nowlistening)
                video_url = self.videosearch.search('%s %s' % (artist.encode('utf-8'),title.encode('utf-8')))
                if not video_url:
                    content = u'正在聽 %s' % (nowlistening)
                else:
                    content = u'正在聽 %s %s' % (nowlistening, video_url)
                self.plurk.plurkAdd(content.encode('utf-8'))
            
    def plurk_login(self):
        username = self.settings.value('username').toString()
        passwd = self.settings.value('password').toString()
        
        if username and passwd:        
            login_result = self.plurk.login(username, passwd, 1)
            if 'success_text' in login_result:
                self.PlurkStatus.setText('Plurk login successful')
                return True
            else:
                return False
            
    @pyqtSlot()
    def on_opt_window_triggered(self):
        ow = option_window(self)
        ow.show()
        
class option_window(QDialog, optionui.Ui_Dialog):
    def __init__(self, parent):
        QDialog.__init__(self, parent)
        self.setupUi(self)
        self.setWindowIcon(parent.W_Icon)
        self.lineEdit_2.setEchoMode(2)
        self.lineEdit.setText(parent.settings.value('username').toString())
        self.pushButton.hide()
        
        self.settings = parent.settings
        
#    @pyqtSlot()
#    def on_pushButton_clicked(self):
#        if parent.plurk_login():
#            self.pushButton.setText('Login successful')
#            self.pushButton.setDisabled()
#        else:
#            self.pushButton.setText('Login fail')
    
    @pyqtSlot()
    def on_buttonBox_accepted(self):
        self.settings.setValue('username', self.lineEdit.text())
        self.settings.setValue('password', self.lineEdit_2.text())

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    trayIcon = mainWidget()
    trayIcon.showMinimized()
    #trayIcon.hide()
    #trayIcon.SystrayIcon.show()
    sys.exit(app.exec_())